<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/1
 * Time: 0:23
 */

namespace Lib\Api;


class Voucher {
    private static $modelName = 'Voucher';

    /** 根据用户ID获取用户代金劵
     * @param $user_id
     * @param $state
     * @return array
     */
    public static function getVoucherList($user_id, $state) {
        $data = array();
        $model = M();
        $field = "a.voucher_range,a.money,a.start_date,a.end_date,a.source,b.name,b.use_money,b.type,b.remark, GROUP_CONCAT(distinct c.game_name) as pname, count(a.id) totals, count(distinct c.id) ptotals";
        $map['a.user_id'] = $user_id;
        if ($state == 0) {
            $map['a.state'] = 2;
            $map['DATE_FORMAT(a.end_date, "%Y-%m-%d")'] = array('egt', date('Y-m-d'));
        } else if ($state == 1) {
            $map['a.state'] = 1;
        } else if ($state == 2) {
            $map['DATE_FORMAT(a.end_date, "%Y-%m-%d")'] = array('elt', date('Y-m-d'));
        }

        $list = $model->table('fs_voucher a')
            ->join('left join fs_voucher_type b on b.id = a.type')
            ->join('left join fs_game_type c on FIND_IN_SET(c.id , a.voucher_range)')
            ->field($field)
            ->where($map)
            ->group('a.money,a.start_date,a.end_date,a.type,a.voucher_range,a.source')
            ->order('a.end_date,a.datetime desc')
            ->select();

        $arr = array();
        if (count($list) > 0) {
            for ($i=0;$i<count($list);$i++) {
                $is_add = true;
                if ($is_add == true) {
                    $voucher['name'] = $list[$i]['name'];
                    $voucher['start_date'] = $list[$i]['start_date'];
                    $voucher['end_date'] = $list[$i]['end_date'];
                    $voucher['money'] = $list[$i]['money'];
                    $voucher['type'] = $list[$i]['type'];
                    $voucher['use_money'] = $list[$i]['use_money'];
                    $voucher['remark'] = $list[$i]['remark'];
                    $voucher['source'] = $list[$i]['source'];
                    $voucher['pname'] = '';
                    if (!empty($list[$i]['pname'])) {
                        $voucher['pname'] = $list[$i]['pname'];
                        $voucher['totals'] = $list[$i]['totals']/$list[$i]['ptotals'];
                    } else {
                        $voucher['totals'] = $list[$i]['totals'];
                    }

                    array_push($arr, $voucher);
                }
            }
        }
        $data['list'] = $arr;
        return $data;
    }
}